using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Threading;
using System.Xml.Serialization;

namespace WillStott.MxAppToolbox
{
	[XmlRoot("UniMsgList")]
	public class UniMsgList
	{
		private  ArrayList m_MsgList;
		public UniMsgList()
		{
			m_MsgList = new ArrayList();
		}

		public void Add( UniMsg msg )
		{
			m_MsgList.Add(msg);
		}

		public UniMsg GetMsg(string MsgId)
		{
			UniMsg msg = null;
			foreach (UniMsg message in m_MsgList)
			{
				if (message.MsgId == MsgId)
				{
					msg = message;
					break;
				}
			}
			if (msg == null)
			{
				msg = GetMsg("0");	
				msg.MsgId = MsgId;
			}
			return msg;
		}

		public void Clear()
		{
			m_MsgList.Clear();
		}

        public static UniMsgList LoadList(Assembly asm, string AssemblyMsgResourceFile)
		{
			UniMsgList rc = null;

			try
			{
				Stream stream = null;
               
				if ((stream = asm.GetManifestResourceStream(AssemblyMsgResourceFile)) == null )
					throw new System.InvalidOperationException("UniMsgList.LoadList(): Msg Resources not found" );

				XmlSerializer serializer = new XmlSerializer(typeof(UniMsgList));
				rc = serializer.Deserialize(stream) as UniMsgList;
			}
			catch(Exception e)
			{
				Program.FatalErrorAbend("UniMsgList.LoadList()", e.Message);
			}
			return rc;
		}

		public void SaveList(string StoreName)
		{
			FileStream fs = null;
			try
			{
				XmlSerializer serializer = new XmlSerializer(typeof(UniMsgList));
				fs = new FileStream(StoreName, FileMode.Create);
				serializer.Serialize(fs, this);
			}
			catch(Exception e)
			{
				Program.FatalErrorAbend("UniMsgList.SaveList()", e.Message);
			}
			finally
			{
				if ( fs != null)
					fs.Close();
			}
		}

		[XmlArray("MessageList")]
		[XmlArrayItem("Message")]
		public UniMsg[] Messages
		{
			get 
			{ 
				UniMsg[] arr = new UniMsg[m_MsgList.Count];
				m_MsgList.CopyTo(arr);
				return arr;
			}
			set
			{
				m_MsgList = new ArrayList(value.Length);
				for (int x = 0; x < value.Length; x++)
					m_MsgList.Add(value[x]);
			}
		}
	}
}
